package ink.xiaobaibai.security;

import ink.xiaobaibai.common.MySecurity;
import ink.xiaobaibai.utils.TokenUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 拦截器
 * @author: 小白白
 * @create: 2021-05-19
 **/

public class ClientInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!this.isValid(request, response)) {
            return false;
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MySecurity.threadLocalId.remove();
    }

    private boolean isValid(HttpServletRequest request, HttpServletResponse response) {
        String jwt = request.getHeader("Authorization");
        if (jwt == null) {
            return false;
        }
        Integer userId = TokenUtil.validJWT(jwt, response);
        if (userId == null) {
            return false;
        }
        MySecurity.threadLocalId.set(userId);
        return true;
    }

}
